<?php

namespace app\apiadmin\service\liveManager;

use app\apiadmin\controller\aliyunVMS\AliyunVmsController;
use app\apiadmin\controller\liveManager\LiveStatus;
use app\apiadmin\model\behavior\LiveUserMongo;
use app\apiadmin\model\liveManager\LiveManagerModel;
use app\apiadmin\service\data\RedisService;
use app\apiadmin\service\invitation\InvitationService;
use app\apiadmin\service\live\SiyuAppService;
use app\apiadmin\service\redis\MsgService;
use app\common\utils\Helper;
use app\common\utils\Res;
use Predis\Client;
use think\facade\Db;
use think\facade\Log;

class LiveManagerService
{

    /**  @var Client redis */
    private $redis;

    /**
     * 直播管理
     */
    public function __construct($config = [], Client $redis = null)
    {
        // LiveManagerModel::add([]);
        $this->redis = $redis;

    }

    public static function list($param, $tutorId = "0")
    {
        $limit = !isset($param['pageSize']) ? 10 : (int) $param['pageSize'];

        $offset = ($param['pageNumber'] - 1) * $limit;
        $keyword = $param['keyword'];

        $whereMap = [];
        $whereMap["del"] = 0;
        if ($keyword) {
            $whereMap[] = ['title', 'like', '%' . $keyword . '%'];
        }
        // if ($param['type'] != 3000) {
        //     $map[] = ['type', '=', $param['type']];
        // }
        $retList = LiveManagerModel::pageMap($whereMap, $offset, $limit);

        for ($i = 0; $i < count($retList); $i++) {
            $item = $retList[$i];
            // $url = env('Live.live_host')."/?liveId=" . $item["id"] . "&tutorId=" . $tutorId.'&';
            $url = self::switchFuWuQi($item['ServerAt'])['liveapp'] . "/?liveId=" . $item["id"] . "&tutorId=" . $tutorId . '&';
            $retList[$i]["shareUrl"] = $url;

            if (!is_null($item["course_sale_ids"])) {
                $ids_list = json_decode($item["course_sale_ids"]);
                $ids = [];
                if (is_array(($ids_list))) {
                    foreach ($ids_list as $key => $value) {
                        $ids[] = $value->id;
                    }
                    $item["course_sale_id"] = $ids;

                } else {
                    $item["course_sale_id"] = [];
                }

            } else {
                $item["course_sale_id"] = [];
            }
            $pinglun_info = DB::table('xh_siyu_manager_pinglun_group')->where(array('manager_id' => $item['id'], 'del' => 0))->select();
            //            $result[$i]['pinglun_info'] = $pinglun_info;
            $arr = array();
            foreach ($pinglun_info as $kk => $vv) {
                $arr[] = intval($vv['group_id']);
            }
            $retList[$i]['pinglunzu_id'] = $arr;
            // 严禁词组
            $yanjin_info = DB::table('xh_siyu_live_manager_forbid')->where(array('live_id' => $item['id'], 'del' => 0))->select();
            $arr = array();
            foreach ($yanjin_info as $yk => $yv) {
                $arr[] = intval($yv['group_id']);
            }
            $retList[$i]['yanjincizu_id'] = $arr;

            $liveStatus = new LiveStatus($item["id"]);
            $retList[$i]["init_people_num"] = $liveStatus->getLikely($item["id"]);

            $url = $retList[$i]["stream_push_url"];
            $retList[$i]["stream_push_url_key"] = basename($url);
            $retList[$i]["stream_push_url"] = str_replace(basename($url), "", $url);
            //复制链接 以结束
            $retList[$i]['playUrl'] = '';
            if ($item['status'] == 2) {
                $retList[$i]['playUrl'] = env('Live.live_host') . '/pages/play/play' . '?code=' . SiyuAppService::encrypt($item['id'], 'E');
            }
        }
        $total_count = LiveManagerModel::pageMapCount($whereMap);

        $live_group_list = Db::name('siyu_live_manager')
            ->field('id,title,live_group')
            ->where(['del' => 0])
            ->group('live_group')
            ->having("count(*)=1")
            ->select()
            ->toArray();

        $ServerAtlist = self::switchFuWuQi();
        $data = [
            'ServerAtlist' => $ServerAtlist,
            'list' => $retList,
            'total' => $total_count,
            'live_group_list' => $live_group_list,
        ];
        return Res::ok($data);

    }

    /**
     * @author: zwx
     * @Description: 根据类型返回不同的域名,空返回所有
     * @param {*} $type
     * @Date: 2024-09-21 09:49:59
     */
    public static function switchFuWuQi($type = '')
    {

        if ($type != '') {
            $fuwuqi = db::table('xh_siyu_live_fuwuqi')->where(['type' => $type, 'del' => 0])->find();
        } else {
            $fuwuqi = db::table('xh_siyu_live_fuwuqi')->where(['del' => 0])->select();
        }

        if (!$fuwuqi) {
            return Res::error('未配置服务器列表');
        }

        return $fuwuqi;

    }

    public static function get($id)
    {
        try {
            $result = LiveManagerModel::find($id);
            return $result;
        } catch (\PDOException $e) {
            throw $e;
        }
    }

    public static function getInfo($id)
    {
        $redis = RedisService::makeService();
        // 如果 reids 中有那么 直接从reids中获取到数据
        $key = env("redis.prefix") . "live:info:" . $id;
        if ($redis->exists($key)) {
            $info = $redis->get($key);
            $live = json_decode($info, true);
            return $live;
        } else {
            // 如果redis 中没有那么 从数据库中查询
            $live = LiveManagerModel::find($id);
            if (empty($live)) {
                return false;
            }

            $info = [
                "title" => $live["title"],
                "status" => $live["status"],
                "start_time" => $live["start_time"],
                "end_time" => $live["service_end_time"],
                "player_type" => $live["player_type"],
                "bg_url" => $live["bg_url"],
                "push_file_name" => $live["push_file_name"],
                "conver_url" => $live["conver"],
                "announcement" => $live["announcement"],
                "stream_app_name" => $live["stream_app_name"],
                "stream_play_url" => $live["stream_play_url"],
                "chatroom_group_id" => $live["chatroom_group_id"],
                "course_sale_ids" => $live["course_sale_ids"],
                "course_sale_id" => $live["course_sale_id"],
                //"pinglun_group_list" => $final_group_list,
                "teacher_name" => "李洁老师",
                "face_url" => "http://1251993779.vod2.myqcloud.com/0f0890f7vodcq1251993779/13dd09e91397757889072110054/euaZ4tp6rFUA.jpg",
            ];

            //
            $info = array_merge($info, $live->toArray());

            // 判断时间 如果当前时间是开播之前10分钟 那么写入缓存 不在从数据库中存储
            if (time() < strtotime($live["start_time"]) - 600) {
                Log::channel("liveInfo")->info("写入redis缓存:" . $live["id"] . "start_time:" . $live["start_time"] . "@" . time());
                $redis->set($key, json_encode($info));
            }
            return $info;
        }
        // $final_group_list = [];
        // $pinglun_group_info = DB::table('xh_siyu_manager_pinglun_group')->where(array('manager_id' => $id, 'del' => 0))->select();
        // foreach ($pinglun_group_info as $k => $v) {
        //     $pinglun_list = DB::table('xh_siyu_pinglun_list')->where(array('groupid' => $v['group_id']))->select();
        //     foreach ($pinglun_list as $kk => $vv) {
        //         $key = substr($vv['fasong_time'], 0, 2) * 60 * 60 + substr($vv['fasong_time'], 3, 2) * 60 + substr($vv['fasong_time'], 6, 2);
        //         $final_group_list[$key][] = $vv['pinglun'];
        //     }
        // }

        // $info = [
        //     "title" => $live["title"],
        //     "status" => $live["status"],
        //     "start_time" => $live["start_time"],
        //     "end_time" => $live["end_time"],
        //     "bg_url" => $live["bg_url"],
        //     "conver_url" => $live["conver"],
        //     "announcement" => $live["announcement"],
        //     "stream_app_name" => $live["stream_app_name"],
        //     "stream_play_url" => $live["stream_play_url"],
        //     "chatroom_group_id" => $live["chatroom_group_id"],
        //     "course_sale_ids" => $live["course_sale_ids"],
        //     "course_sale_id" => $live["course_sale_id"],
        //     "pinglun_group_list" => $final_group_list,
        //     "teacher_name" => "李洁老师",
        //     "face_url" => "http://1251993779.vod2.myqcloud.com/0f0890f7vodcq1251993779/13dd09e91397757889072110054/euaZ4tp6rFUA.jpg",
        // ];

        //return $info;
    }

    /**
     * 判断用户是否已经看过直播内容
     * @param mixed $live_id
     * @param mixed $user_id
     * @param mixed $planId
     * @return bool
     */
    public static function isWatchedLiveContent($live_id, $user_id)
    {
        $whitelist = Db::table('xh_siyu_live_whitelist')->where('user_id', $user_id)->count();
//        $planInfo = Db::name('xh_siyu_invitation_plan')->where(['id' => $planId, 'del' => 0])->find();
//        if ($whitelist > 0 || !$planInfo) {
        if ($whitelist > 0) {
            return false; //在白名单内不验证
        }
        try {
            $liveIndo = DB::name('siyu_live_manager')->where(['id' => $live_id])->find();
            $w = Db::table('xh_siyu_live_manager')->alias('lm')
                ->join('xh_siyu_user_order_zhujiao_log zl', 'lm.id=zl.live_id')
                ->where('lm.del', 0)
                ->where('lm.status', 2)
                ->where('lm.push_file_name', $liveIndo['push_file_name'])
                ->where('zl.user_id', $user_id)
                ->count();
            if ($w > 0) {
                return true;
            }
        } catch (\Exception $e) {
            Log::error('视频验证错误：' . $e->getMessage());
        }
        return false; //报错不验证

    }

    public static function getStatus($id)
    {
        $result = LiveManagerModel::find($id);
        if (!empty($result)) {
            return Res::ok([
                "status" => $result["status"],
                "start_time" => $result["start_time"],
            ]);
        }
        return Res::error("直播不存在");
    }

    public static function add($param)
    {
        try {
            $param["del"] = 0;
            $param["status"] = 0;
            //unset($param["z_id"]);
            unset($param["create_time"]); // 注释掉 create_time  这个字段只能有 数据库 产生
            // 添加 course_sale_ids 从 course_sale_id 这个前端数组中
            $course_sale_id = $param["course_sale_id"];
            if (isset($param["id"])) {
                unset($param["id"]);
            }
            $param["course_sale_id"] = 0;

            if (is_array($course_sale_id)) {
                // 使用 $course_sale_id  直接使用字符串
                $param["course_sale_ids"] = self::loadCourseByIds($course_sale_id);
            }
            if ($param['venue'] == 1) {
                $maxId = Db::query("SELECT AUTO_INCREMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?", [env('database.database', 'xiaoxuehua'), 'xh_siyu_live_manager']);
                $maxId = $maxId[0]['AUTO_INCREMENT'];
                $param['live_group'] = date('Ymd', time()) . '-' . $maxId;
            }

            $ret = LiveManagerModel::add($param);
            //评论组相关数据
            $pinglunzu_id = $param["pinglunzu_id"];
            // 先 删除之前的 绑定的评论组
            DB::table('xh_siyu_manager_pinglun_group')->where(array('manager_id' => $ret, 'del' => 0))->delete();
            if (is_array($pinglunzu_id) && $ret) {
                $insertData = [];
                foreach ($pinglunzu_id as $v) {
                    $d = [];
                    $d['manager_id'] = $ret;
                    $d['group_id'] = $v;
                    $d['createtime'] = date("Y-m-d H:i:s");
                    $d['del'] = 0;
                    $insertData[] = $d;
                }
                if (!empty($insertData)) {
                    DB::table('xh_siyu_manager_pinglun_group')->insertAll($insertData);
                }
            }
            unset($param["pinglunzu_id"]);

            //严禁词组相关数据
            $yanjincizu_id = $param["yanjincizu_id"];
            // 先 删除之前的 绑定的严禁词组
            DB::table('xh_siyu_live_manager_forbid')->where(array('live_id' => $ret, 'del' => 0))->delete();
            if (is_array($yanjincizu_id) && $ret) {
                $forbidData = [];
                foreach ($yanjincizu_id as $v) {
                    $dt = [];
                    $dt['live_id'] = $ret;
                    $dt['group_id'] = $v;
                    $dt['createtime'] = date("Y-m-d H:i:s");
                    $dt['del'] = 0;
                    $forbidData[] = $dt;
                }
                if (!empty($forbidData)) {
                    DB::table('xh_siyu_live_manager_forbid')->insertAll($forbidData);
                }
            }
            unset($param["yanjincizu_id"]);

            Log::channel("liveInfo")->info("add:liveInfo:" . json_encode($param));
            Log::channel("liveInfo")->info("add:liveInfo:ret:" . json_encode($ret));
            return $ret;

        } catch (\PDOException $e) {
            Log::channel("liveInfo")->error("add:liveInfo:error:" . $e->getMessage());
            throw $e;
        }
    }

    public static function loadCourseByIds(array $ids)
    {
        $list = Db::name("siyu_course")->where("id", "in", $ids)->select();
        $data = array();
        foreach ($list as $k => $v) {
            $a = array();
            $a['id'] = $v['id'];
            $a['courseid'] = $v['id'];
            $a['img'] = $v['img'];
            $a['title'] = $v['name'];
            $a['detail'] = $v['detail'];
            $a['fee'] = $v['fee'];
            $a['sort'] = $v['sort'];

            $a['xianjia'] = '¥' . number_format($v['fee'] / 100, 2);
            $a['yuanjia'] = '¥' . number_format($v['sale'] / 100, 2);

            $b = array();
            $b[0]['name'] = '热销5万+';
            $b[0]['style'] = 'color:red;border-color:red;';

            $b[1]['name'] = '永久有效';
            $b[1]['style'] = 'color:red;border-color:red;';

            $a['biaoqian'] = $b;

            $data[] = $a;
        }
        if (!empty($data)) {
            $ret = json_encode($data);
            return $ret;
        } else {
            return json_encode([]);
        }

    }

    public static function update($id, $param)
    {
        try {
            unset($param["create_time"]); // 注释掉 create_time  更新的时候 这个字段不更新
            unset($param["stream_push_url_key"]); // 注释掉  stream_push_url_key  更新的时候 这个字段不更新
            unset($param["stream_push_url"]); // 注释掉  stream_push_url  更新的时候 这个字段不更新
            unset($param['playUrl']);
            $info = LiveManagerModel::find($id);
            if (time() > strtotime($info["start_time"]) - 600) {
                throw new \Exception("直播开播前十分钟不能修改!");
            }
            Log::channel("liveInfo")->info("update:liveInfo:" . json_encode($info));
            if (!empty($info)) {
                $param["update_time"] = date("Y-m-d H:i:s");
                unset($param["shareUrl"]);

                // 添加 course_sale_ids 从 course_sale_id 这个前端数组中
                $course_sale_id = $param["course_sale_id"];
                $param["course_sale_id"] = 0;

                if (is_array($course_sale_id)) {
                    // 使用 $course_sale_id  直接使用字符串
                    $param["course_sale_ids"] = self::loadCourseByIds($course_sale_id);
                }

                //评论组相关数据
                $pinglunzu_id = $param["pinglunzu_id"];
                // 先 删除之前的 绑定的评论组
                DB::table('xh_siyu_manager_pinglun_group')->where(array('manager_id' => $id, 'del' => 0))->delete();
                if (is_array($pinglunzu_id) && $id) {
                    $insertData = [];
                    foreach ($pinglunzu_id as $v) {
                        $d = [];
                        $d['manager_id'] = $id;
                        $d['group_id'] = $v;
                        $d['createtime'] = date("Y-m-d H:i:s");
                        $d['del'] = 0;

                        $insertData[] = $d;
                    }
                    if (!empty($insertData)) {
                        DB::table('xh_siyu_manager_pinglun_group')->insertAll($insertData);
                    }
                }
                unset($param["pinglunzu_id"]);

                //严禁词组相关数据
                $yanjincizu_id = $param["yanjincizu_id"];
                // 先 删除之前的 绑定的严禁词组
                DB::table('xh_siyu_live_manager_forbid')->where(array('live_id' => $id, 'del' => 0))->delete();
                if (is_array($yanjincizu_id) && $id) {
                    $forbidData = [];
                    foreach ($yanjincizu_id as $v) {
                        $dt = [];
                        $dt['live_id'] = $id;
                        $dt['group_id'] = $v;
                        $dt['createtime'] = date("Y-m-d H:i:s");
                        $dt['del'] = 0;
                        $forbidData[] = $dt;
                    }
                    if (!empty($forbidData)) {
                        DB::table('xh_siyu_live_manager_forbid')->insertAll($forbidData);
                    }
                }
                unset($param["yanjincizu_id"]);

                //$ret = $info->update($param);
                $ret = LiveManagerModel::where(["id" => $id, "status" => 0])->cache(false)->update($param);
                Log::channel("liveInfo")->info("update:liveInfo:param:" . json_encode($param));
                Log::channel("liveInfo")->info("update:liveInfo:result:" . json_encode($ret));
                return $ret;
            } else {
                Log::channel("liveInfo")->info("update:liveInfo:can't find it:" . $id);
                return false;
            }
        } catch (\Exception $e) {
            Log::channel("liveInfo")->error("update:liveInfo:error:" . $e->getMessage());
            throw $e;
            //return false;
        }
    }

    public static function del($id)
    {
        try {
            Log::channel("liveInfo")->info("del:liveInfo:" . json_encode($id));
            $result = LiveManagerModel::find($id);
            Log::channel("liveInfo")->info("del:liveInfo:befor:" . json_encode($result));
            if (empty($result)) {
                Log::channel("liveInfo")->info("del:liveInfo:err:" . "can't find it!" . $id);
                return Res::error('数据不存在');
            }
            // 删除绑定的评论组
            DB::table('xh_siyu_manager_pinglun_group')->where(array('manager_id' => $id, 'del' => 0))->delete();
            // 删除绑定的严禁词组
            DB::table('xh_siyu_live_manager_forbid')->where(array('live_id' => $id, 'del' => 0))->delete();
            // 删除直播
            $ret = LiveManagerModel::where(["id" => $id])->cache(false)->update(["del" => 1]);
            Log::channel("liveInfo")->info("del:liveInfo:ret:" . $ret);
            return Res::ok($ret);
        } catch (\PDOException $e) {
            Log::channel("liveInfo")->error("del:liveInfo:error:" . $e->getMessage());
            return Res::error($e->getMessage());
        }
    }

    public static function end($id)
    {
        try {
            Log::channel("liveInfo")->info("end:liveInfo:" . json_encode($id));
            $result = LiveManagerModel::find($id);
            Log::channel("liveInfo")->info("end:liveInfo:befor:" . json_encode($result));
            if (empty($result)) {
                Log::channel("liveInfo")->info("end:liveInfo:err:" . "can't find it!" . $id);
                return Res::error('数据不存在');
            }
            //$ret = LiveManagerModel::where(["id" => $id])->cache(false)->update(["status" => 2]);
            $ret = LiveManagerService::updateStatusByLiveId($id, 2, time());
            Log::channel("liveInfo")->info("end:liveInfo:ret:" . $ret);
            return Res::ok($ret);
        } catch (\PDOException $e) {
            Log::channel("liveInfo")->error("end:liveInfo:error:" . $e->getMessage());
            return Res::error($e->getMessage());
        }
    }

    public static function batchRemove($param)
    {
        try {

            LiveManagerModel::del($param);

            return Res::ok();
        } catch (\PDOException $e) {
            return Res::error($e->getMessage());
        }
    }

    public static function getLiveInfoByTaskId($id)
    {
        return LiveManagerModel::where(["css_task_id" => $id])->cache(false)->find();
    }

    public static function updateStatusByTaskId($task_id, $status, $int_time)
    {
        try {
            Log::channel("liveInfo")->info("updateStatusByTaskId:liveInfo:id:" . json_encode($task_id));
            $info = LiveManagerModel::where(["css_task_id" => $task_id])->find();
            Log::channel("liveInfo")->info("updateStatusByTaskId:liveInfo:id:info:" . json_encode($info));

            if (empty($info)) {
                return "直播不存在";
            }
            $info = $info->toArray();
            // $info->status = $status;
            // $info->save();

            // 如果 liveinfo 的 status ==1 并且 status == 1 那么放弃 更新
            if ($info["live_type"] == 1 && $info["status"] == 1 && $status == 1) {
                Log::channel("liveInfo")->info("updateStatusByTaskId:liveInfo:id:skip:live_info_event:start" . json_encode($info));
                return "直播正在服务中";
            }

            // 更新缓存 live:info:id2
            $updateData = ["status" => $status];
            if ($status == 1) {
                $updateData["service_start_time"] = $int_time;
                $info["service_start_time"] = $int_time;
            } else if ($status == 2) {
                $updateData["service_end_time"] = $int_time;
                $info["service_end_time"] = $int_time;
            }
            $retUpate = LiveManagerModel::where(["css_task_id" => $task_id])->update($updateData);
            Log::channel("liveInfo")->info("updateStatusByTaskId:liveInfo:retUpate:" . json_encode($retUpate));

            $info["status"] = $status;
            $info["update_by"] = "updateStatusByTaskId";

            $info["conver_url"] = $info["conver"];

            $key = env("redis.prefix") . "live:info:" . $info["id"];
            $redis = RedisService::makeService();
            $retRedisStatus = $redis->set($key, json_encode($info));
            //  redis 发送消息
            $redis->publish(env("redis.prefix") . "live_info_event", json_encode([
                "liveId" => '' . $info["id"],
                "command" => "flash_live_info",
                "params" => "",
            ]));
            if ($status == 1) {
                MsgService::sendStartLiveMessage($info['id']); // 装载严禁词库
                $redis->publish(env("redis.prefix") . "live_info_event", json_encode([
                    "liveId" => '' . $info["id"],
                    "command" => "live_start",
                    "params" => "",
                ]));

            } else if ($status == 2) {
                MsgService::sendEndLiveMessage($info['id']); // 卸载严禁词库
                $redis->publish(env("redis.prefix") . "live_info_event", json_encode([
                    "liveId" => '' . $info["id"],
                    "command" => "live_end",
                    "params" => "",
                ]));

                // 添加到 lpush 
                $redis->lpush("live_end_for_tag", $info["id"]);

            }

            Log::channel("liveInfo")->info("写入redis缓存:updateStatusByTaskId:" . $info["id"] . "start_time:" . $info["start_time"] . "@" . time());
            Log::channel("liveInfo")->info("updateStatusByTaskId:liveInfo:retRedisStatus:" . json_encode($retRedisStatus));
            return true;
        } catch (\PDOException $e) {
            Log::channel("liveInfo")->error("updateStatusByTaskId:liveInfo:error:" . $e->getMessage());
            return $e->getMessage();
        }

    }

    public static function updateStatusByLiveId($liveId, $status, $int_time)
    {
        try {
            Log::channel("liveInfo")->info("updateStatusByTaskId:liveInfo:id:" . json_encode($liveId));
            $info = LiveManagerModel::where(["id" => $liveId])->find();
            Log::channel("liveInfo")->info("updateStatusByTaskId:liveInfo:id:info:" . json_encode($info));

            if (empty($info)) {
                return "直播不存在";
            }
            $info = $info->toArray();
            // $info->status = $status;
            // $info->save();

            // 更新缓存 live:info:id
            $updateData = ["status" => $status];
            if ($status == 1) {
                $updateData["service_start_time"] = $int_time;
                $info["service_start_time"] = $int_time;
            } else if ($status == 2) {
                $updateData["service_end_time"] = $int_time;
                $info["service_end_time"] = $int_time;
            }
            $retUpate = LiveManagerModel::where(["id" => $liveId])->update($updateData);
            Log::channel("liveInfo")->info("updateStatusByTaskId:liveInfo:retUpate:" . json_encode($retUpate));

            $info["status"] = $status;
            $info["conver_url"] = $info["conver"];

            $info["update_by"] = "updateStatusByLiveId";

            $key = env("redis.prefix") . "live:info:" . $info["id"];
            $redis = RedisService::makeService();
            $retRedisStatus = $redis->set($key, json_encode($info));
            //  redis 发送消息
            $redis->publish(env("redis.prefix") . "live_info_event", json_encode([
                "liveId" => '' . $info["id"],
                "command" => "flash_live_info",
                "params" => "",
            ]));
            if ($status == 1) {
                MsgService::sendStartLiveMessage($info['id']); // 装载严禁词库
                $redis->publish(env("redis.prefix") . "live_info_event", json_encode([
                    "liveId" => '' . $info["id"],
                    "command" => "live_start",
                    "params" => "",
                ]));

            } else if ($status == 2) {
                MsgService::sendEndLiveMessage($info['id']); // 卸载严禁词库
                $redis->publish(env("redis.prefix") . "live_info_event", json_encode([
                    "liveId" => '' . $info["id"],
                    "command" => "live_end",
                    "params" => "",
                ]));

            }

            Log::channel("liveInfo")->info("写入redis缓存:updateStatusByTaskId:" . $info["id"] . "start_time:" . $info["start_time"] . "@" . time());
            Log::channel("liveInfo")->info("updateStatusByTaskId:liveInfo:retRedisStatus:" . json_encode($retRedisStatus));
            return true;
        } catch (\PDOException $e) {
            Log::channel("liveInfo")->error("updateStatusByTaskId:liveInfo:error:" . $e->getMessage());
            return $e->getMessage();
        }

    }

    // 用群组ID获取直播ID
    public static function getLiveIdByGroupId($groupId)
    {

        $livestatus = new LiveStatus(null);
        $liveId = $livestatus->GetLiveIdByGroupId($groupId);
        return $liveId;

        // try {
        //     $result = LiveManagerModel::where(["chatroom_group_id" => $groupId])->cache(false)->find();
        //     if (empty($result)) {
        //         return false;
        //     }
        //     return $result["id"];
        // } catch (\PDOException $e) {
        //     throw $e;
        // }
    }

    /**
     * 匹配公域订单
     * @param $wxUnionId
     * @param $isAssociation
     * @return number
     * @author cc
     */
    public static function checkXhOrder($wxUnionId, $isAssociation = false)
    {

        if (empty($wxUnionId)) {
            return false;
        }

        $where = [];
        $where[] = ['wx_union_id', '=', $wxUnionId];
        $where[] = ['pay_state', '=', 1];
        if (!$isAssociation) {
            $where[] = ['is_association_siyu', '=', 0];
        }
        $where[] = ['pingtai', 'in', [1, 2, 4, 6]];
        $where[] = ['pay_time', '<', date('Y-m-d H:i:s')];
        $orderArray = Db::table('xh_order_1')
            ->where($where)
            ->field('id,wx_union_id,order_status,order_num,out_order_no,pay_time')
            ->order('id desc')
            ->select();
        $number = $orderArray->count();
        //只有一单
        if ($number == 1) {
            return $orderArray[0]['id'];
        }
        //如果有多单
        if ($number > 1) {
            //如果一单私域匹配上了多单公域
            //先查是否有效公域订单
            $gyvalid = $gyinvalid = [];
            foreach ($orderArray->toArray() as $v) {
                if ($v['order_status'] <= 1) {
                    $gyvalid[] = $v;
                } else {
                    $gyinvalid[] = $v;
                }
            }
            //判断有效单有几单
            if (count($gyvalid) > 0) {
                return $gyvalid[0]['id'];
            } else {
                return $gyinvalid[0]['id'];
            }
        }
    }

    /**
     * 直播订单状态更改
     * @param $liveId '直播间id'
     * @param $session '场次'
     * @param $orderId '公域订单id'
     * @param $type '当前状态 0：无、1:邀约、2:到课、3:成交'
     * @param $unionId '用户union_id'
     * @param $tutorId '邀请人id'
     * @param $siyuId '私域订单id'
     * @param $money '成交金额'
     * @return bool|string
     * @author cc
     */
    public static function getLiveOrderState($liveId, $session, $orderId, $type, $unionId = '', $tutorId = '', $siyuId = '', $money = '')
    {
        try {
            $orderInfo = Db::table('xh_order_1')->where('id', $orderId)->find();
            if (!$orderInfo) {
                throw new \Exception("订单不存在!");
            }
            $date = date('Y-m-d H:i:s');
            $data = $changes = [];
            $yaoyue1 = $yaoyue2 = $daoke1 = $daoke2 = 0;
            switch ($type) {
                case 1:
                    $data = [
                        'new_yaoyue_tag' => 1,
                        'new_yaoyue_tag_time' => $date,
                    ];
                    if ($session == 1) {
                        $yaoyue1 = 1;
                        $changes = [
                            'yaoyue_day1' => 1,
                        ];
                    }
                    if ($session == 2) {
                        $yaoyue2 = 1;
                        $changes = [
                            'yaoyue_day2' => 1,
                        ];
                    }
                    break;
                case 2:
                    $data = [
                        'new_daoke_tag' => 1,
                        'new_daoke_tag_time' => $date,
                    ];
                    if ($session == 1) {
                        $yaoyue1 = 1;
                        $daoke1 = 1;
                        $changes = [
                            'yaoyue_day1' => 1,
                            'daoke_day1' => 1,
                        ];
                    }
                    if ($session == 2) {
                        $yaoyue2 = 1;
                        $daoke2 = 1;
                        $changes = [
                            'yaoyue_day2' => 1,
                            'daoke_day2' => 1,
                        ];
                    }
                    break;
                case 3:
                    $data = [
                        'new_chengjiao_tag' => 1,
                        'new_chengjiao_tag_time' => $date,
                    ];
                    if ($session == 1) {
                        $yaoyue1 = 1;
                        $daoke1 = 1;
                        $changes = [
                            'yaoyue_day1' => 1,
                            'daoke_day1' => 1,
                        ];
                    }
                    if ($session == 2) {
                        $yaoyue2 = 1;
                        $daoke2 = 1;
                        $changes = [
                            'yaoyue_day2' => 1,
                            'daoke_day2' => 1,
                        ];
                    }
                    break;
                default:
                    break;
            }

            if ($type != 0 && !empty($data)) {
                // 修改 order_1 订单状态
                Db::table('xh_order_1')->where('id', $orderId)->update($data);

                $changesInfo = Db::table('xh_order_changes')->where('order_id', $orderId)->find();
                if (!$changesInfo) {
                    Db::table('xh_order_changes')->insert([
                        'order_id' => $orderId,
                        'yaoyue_day1' => $yaoyue1,
                        'yaoyue_day2' => $yaoyue2,
                        'daoke_day1' => $daoke1,
                        'daoke_day2' => $daoke2,
                        'time' => date('Y-m-d H:i:s'),
                    ]);
                } else {
                    Db::table('xh_order_changes')->where('id', $changesInfo['id'])->update($changes);
                }
            }

//            if ($type == 2) {
//                Log::channel("liveOrderInfo")->info("liveOrderInfo:daoke：" . $unionId . ' - ' . $date);
//                if (!empty($unionId)) {
//                    $where = [];
//                    $where[] = ['liveId', '=', $liveId];
//                    $where[] = ['venue', '=', $session];
//                    $where[] = ['wx_unionid', '=', $unionId];
//                    Db::table('xh_siyu_invitation_user')->where($where)->update([
//                        'signin_status' => 2,
//                        'signin_time' => $date,
//                    ]);
//                }
//            }
            if ($type == 3) {
                Log::channel("liveOrderInfo")->info("liveOrderInfo:chengjiao：" . $unionId . ' - ' . $siyuId . ' - ' . $date);
                Db::table('xh_order_1')->where('id', $orderId)->update(['is_association_siyu' => 1]);
                if (!empty($siyuId) && !empty($tutorId) && !empty($unionId)) {
                    $userName = Db::table('xh_siyu_sys_member')->where('uid', $tutorId)->value('user_name');
                    $where = [];
                    $where[] = ['liveId', '=', $liveId];
                    $where[] = ['venue', '=', $session];
                    $where[] = ['wx_unionid', '=', $unionId];
                    $where[] = ['sender', '=', $userName];
                    $a = Db::table('xh_siyu_invitation_user')->where($where)->update([
                        'chengjiao_status' => 2,
                        'chengjiao_time' => $date,
                        'chengjiao_money' => $money,
                        'gongyu_order_id' => $orderId,
                        'siyu_order_id' => $siyuId,
                    ]);
                    $d['remark'] = date('Y-m-d H:i:s') . '--Db::table(xh_siyu_invitation_user)->3-- ' . $a . '-----' . json_encode($where);
                    DB::table('xh_siyu_user_remark')->save($d);
                }
            }
            // 新增/修改 直播订单状态
            $orderLiveDetail = Db::table('xh_order_live_detail')->where(['order_id' => $orderInfo['id'], 'live_id' => $liveId, 'session' => $session])->find();
            if (!$orderLiveDetail) {
                if ($type == 1) {
                    $data = [
                        'order_id' => $orderInfo['id'],
                        'live_id' => $liveId,
                        'session' => $session,
                        'type' => $type,
                        'del' => 0,
                        'time' => $date,
                    ];
                    Db::table('xh_order_live_detail')->insert($data);
                }
            } else {
                Db::table('xh_order_live_detail')->where('id', $orderLiveDetail['id'])->update(['type' => $type]);
            }

            return true;
        } catch (\PDOException $e) {
            Log::channel("liveOrderInfo")->error("add:liveOrderInfo:error:" . $e->getMessage());
            throw $e;
        }
    }

    /**
     * @param $conditions
     * @param array $fields
     * @return array
     * Created by chenyawei on 2024/7/23
     * Description:根据条件查询单条
     */
    public static function findOneWith($conditions, $fields = '*')
    {
        $data = Db::table('xh_siyu_live_manager')->where($conditions)->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    public static function findWith($conditions, $fields = '*')
    {
        $data = Db::table('xh_siyu_live_manager')->where($conditions)->field($fields)->select();
        return $data ? $data->toArray() : [];
    }
    /**
     * @param $conditions
     * @return array
     * Created by chenyawei on 2024/7/23
     * Description:根据条件查询数量
     */
    public static function countWith($conditions)
    {
        return Db::table('xh_siyu_live_manager')->where($conditions)->count();
    }

    /**
     * @param $param
     * @return \think\response\Json
     * Created by chenyawei on 2024/7/25
     * Description:直播数据统计
     */
    public function liveData($param)
    {
        $whereMap['del'] = 0;
        $whereStr = '';
        if (!empty($param['live_group'])) {
            $whereMap['live_group'] = $param['live_group'];
            $whereStr = ' and m.live_group = "' . $param['live_group'] . '" ';
        }
        $limit = $param['limit'] ?? 10;
        $offset = $param['offset'] ?? 1;
        $fields = ' live_group,
                    MAX(CASE WHEN venue = 1 THEN id END) AS one_id,
                    MAX(CASE WHEN venue = 2 THEN id END) AS two_id,
                    MAX(CASE WHEN venue = 1 THEN start_time END) AS one_start_time,
                    MAX(CASE WHEN venue = 2 THEN start_time END) AS two_start_time,
                    MAX(CASE WHEN venue = 1 THEN yaoyue_num END) AS one_yaoyue_num,
                    MAX(CASE WHEN venue = 2 THEN yaoyue_num END) AS two_yaoyue_num,
                    MAX(CASE WHEN venue = 1 THEN daoke_num END) AS one_daoke_num,
                    MAX(CASE WHEN venue = 2 THEN daoke_num END) AS two_daoke_num,
                    sum(live_deal_num) AS live_deal_num';
        $sql = "(SELECT
                 m.id,
                 m.start_time,
                 m.end_time,
                 m.venue,
                 m.live_group,
                 sum( CASE WHEN u.signin_status = 2 THEN 1 ELSE 0 END ) AS daoke_num,
                 sum( CASE WHEN u.invitation_status = 2 THEN 1 ELSE 0 END ) AS yaoyue_num,
                 sum( CASE WHEN u.signin_status = 2 AND chengjiao_status = 2 THEN 1 ELSE 0 END ) AS live_deal_num
                FROM
                 xh_siyu_live_manager m LEFT JOIN
                 (
                    SELECT liveId, MAX( signin_status ) as signin_status, MAX( chengjiao_status ) as chengjiao_status, MAX( invitation_status ) as invitation_status FROM xh_siyu_invitation_user where del = 0 GROUP BY liveId, venue, wx_unionid
                    ) AS u ON u.liveId = m.id
                WHERE
                 m.del = 0 " . $whereStr . "
                GROUP BY
                 m.id
                 ) a
                 GROUP BY
                live_group
               ORDER BY
                start_time DESC ";

        $total = Db::name('siyu_live_manager')->where($whereMap)->group('live_group')->count("*");
        $list = Db::query('select' . $fields . ' from ' . $sql . ' limit ' . $limit . ' offset ' . $offset);
        if (empty($list)) {
            return Res::ok(compact('list', 'total'));
        }
        foreach ($list as &$item) {
            $where = [];
            $where[] = ['wx_unionid', '<>', ''];
            $where[] = ['signin_status', '>', 0];
            $unionIdArr1 = Db::table('xh_siyu_invitation_user')->where('liveId', $item['one_id'])->where($where)->group('wx_unionid')->column('wx_unionid');
            $unionIdArr2 = Db::table('xh_siyu_invitation_user')->where('liveId', $item['two_id'])->where($where)->group('wx_unionid')->column('wx_unionid');
            $orderUnionIdArr1 = Db::table('xh_siyu_user_order_zhujiao_log')->where('live_id', $item['one_id'])->where('xh_order_union_id', 'in', $unionIdArr1)->group('xh_order_union_id')->column('xh_order_union_id');
            $orderUnionIdArr2 = Db::table('xh_siyu_user_order_zhujiao_log')->where('live_id', $item['two_id'])->where('xh_order_union_id', 'in', $unionIdArr2)->group('xh_order_union_id')->column('xh_order_union_id');
            // 获取到课 未在zhujiao_log登录的union_id
            $orderUnionIdArray1 = array_diff($unionIdArr1, $orderUnionIdArr1);
            $orderUnionIdArray2 = array_diff($unionIdArr2, $orderUnionIdArr2);
            // 获取使用第二微信登录的 user_id
            $userIdArr1 = Db::table('xh_siyu_user_order_zhujiao_log')->where('live_id', $item['one_id'])->where('user_union_id', 'in', $orderUnionIdArray1)->group('user_union_id')->column('user_id');
            $userIdArr2 = Db::table('xh_siyu_user_order_zhujiao_log')->where('live_id', $item['two_id'])->where('user_union_id', 'in', $orderUnionIdArray2)->group('user_union_id')->column('user_id');

            $map1 = [];
            $map1[] = ['live_id', '=', $item['one_id']];
            $map1[] = ['xh_order_union_id', 'in', $unionIdArr1];
            $userIdDay1Arr = Db::table('xh_siyu_user_order_zhujiao_log')->where($map1)->group('xh_order_union_id')->column('user_id');
            $map2 = [];
            $map2[] = ['live_id', '=', $item['two_id']];
            $map2[] = ['xh_order_union_id', 'in', $unionIdArr2];
            $userIdDay2Arr = Db::table('xh_siyu_user_order_zhujiao_log')->where($map2)->group('xh_order_union_id')->column('user_id');
            $userIdDay1Arr = array_merge($userIdDay1Arr, $userIdArr1);
            $userIdDay2Arr = array_merge($userIdDay2Arr, $userIdArr2);

            $online_15_num1 = $online_30_num1 = $online_45_num1 = $online_60_num1 = $online_75_num1 = $online_gt75_num1 = $mongo_num1 = 0;
            $online_15_num2 = $online_30_num2 = $online_45_num2 = $online_60_num2 = $online_75_num2 = $online_gt75_num2 = $mongo_num2 = 0;
            if ($item['one_id'] > 0) {
                $liveUserArrDay1 = LiveUserMongo::list_array($item['one_id']);
                if (!empty($liveUserArrDay1)) {
                    foreach ($liveUserArrDay1 as $day1) {
                        if (isset($day1['wx_unionid']) && !empty($day1['wx_unionid']) && in_array($day1['live_user_id'], $userIdDay1Arr)) {
                            if ((isset($day1['online_time']) && $day1['online_time'] <= (60 * 15)) || !isset($day1['online_time']) || empty($day1['online_time'])) {
                                $online_15_num1++;
                            }
                            if (isset($day1['online_time']) && $day1['online_time'] > (60 * 15) && $day1['online_time'] <= (60 * 30)) {
                                $online_30_num1++;
                            }
                            if (isset($day1['online_time']) && $day1['online_time'] > (60 * 30) && $day1['online_time'] <= (60 * 45)) {
                                $online_45_num1++;
                            }
                            if (isset($day1['online_time']) && $day1['online_time'] > (60 * 45) && $day1['online_time'] <= (60 * 60)) {
                                $online_60_num1++;
                            }
                            if (isset($day1['online_time']) && $day1['online_time'] > (60 * 60) && $day1['online_time'] <= (60 * 75)) {
                                $online_75_num1++;
                            }
                            if (isset($day1['online_time']) && $day1['online_time'] > (60 * 75)) {
                                $online_gt75_num1++;
                            }
                            $mongo_num1++;
                        }
                    }
                }
            }
            if ($item['two_id'] > 0) {
                $liveUserArrDay2 = LiveUserMongo::list_array($item['two_id']);
                if (!empty($liveUserArrDay2)) {
                    foreach ($liveUserArrDay2 as $day2) {
                        if (isset($day2['wx_unionid']) && !empty($day2['wx_unionid']) && in_array($day2['live_user_id'], $userIdDay2Arr)) {
                            if ((isset($day2['online_time']) && $day2['online_time'] <= (60 * 15)) || !isset($day2['online_time']) || empty($day2['online_time'])) {
                                $online_15_num2++;
                            }
                            if (isset($day2['online_time']) && $day2['online_time'] > (60 * 15) && $day2['online_time'] <= (60 * 30)) {
                                $online_30_num2++;
                            }
                            if (isset($day2['online_time']) && $day2['online_time'] > (60 * 30) && $day2['online_time'] <= (60 * 45)) {
                                $online_45_num2++;
                            }
                            if (isset($day2['online_time']) && $day2['online_time'] > (60 * 45) && $day2['online_time'] <= (60 * 60)) {
                                $online_60_num2++;
                            }
                            if (isset($day2['online_time']) && $day2['online_time'] > (60 * 60) && $day2['online_time'] <= (60 * 75)) {
                                $online_75_num2++;
                            }
                            if (isset($day2['online_time']) && $day2['online_time'] > (60 * 75)) {
                                $online_gt75_num2++;
                            }
                            $mongo_num2++;
                        }
                    }
                }
            }
            // day1 到课率
            $item['one_daoke_rate'] = Helper::getRate($item['one_daoke_num'], $item['one_yaoyue_num']);
            // day2 到课率
            $item['two_daoke_rate'] = Helper::getRate($item['two_daoke_num'], $item['two_yaoyue_num']);
            // 直播间成交数
            $liveIdArr = [];
            if (!empty($item['one_id'])) {
                array_push($liveIdArr, $item['one_id']);
            }
            if (!empty($item['two_id'])) {
                array_push($liveIdArr, $item['two_id']);
            }
            $dealInfoList = $this->getDealNum($liveIdArr);
            $unliveDeal = isset($dealInfoList['resUnliveDeal']) ? $dealInfoList['resUnliveDeal'] : [];
            $resNoPay = isset($dealInfoList['resNoPay']) ? $dealInfoList['resNoPay'] : [];
            $dealInfoNoPay = array_pop($resNoPay);
            $dealInfoUnliveDeal = array_pop($unliveDeal);
            //总邀约数
            $item['total_yaoyue_num'] = $item['one_yaoyue_num'] + $item['two_yaoyue_num'];
            // 课后成交数
            $item['unlive_deal_num'] = $unlive_deal_num = isset($dealInfoUnliveDeal['unlive_deal_num']) ? $dealInfoUnliveDeal['unlive_deal_num'] : 0;
            // 课后成交率
            $item['unlive_deal_rate'] = Helper::getRate($unlive_deal_num, $item['two_daoke_num']);
            // 直播成交率
            $item['live_deal_rate'] = Helper::getRate($item['live_deal_num'], $item['two_daoke_num']);

            // 总成交数
            $item['total_deal_num'] = $item['live_deal_num'] + $unlive_deal_num;
            // 总成交率
            $item['total_deal_rate'] = Helper::getRate($item['total_deal_num'], $item['two_daoke_num']);
            // 邀约总成交率
            $item['total_yaoyu_chengjiao_lv'] = Helper::getRate($item['total_deal_num'], $item['two_yaoyue_num']);
            // 未支付数
            $item['no_pay_num'] = isset($dealInfoNoPay['no_pay_num']) ? $dealInfoNoPay['no_pay_num'] : 0;
            $userIdDay1Num = count($userIdDay1Arr);
            $userIdDay2Num = count($userIdDay2Arr);
            $difference1 = $mongo_num1 != $userIdDay1Num ? ($userIdDay1Num - $mongo_num1) : 0;
            $difference2 = $mongo_num2 != $userIdDay2Num ? ($userIdDay2Num - $mongo_num2) : 0;
            // day1day2观看人数
            $item['online_15_num1'] = $online_15_num1 + $difference1;
            $item['online_30_num1'] = $online_30_num1;
            $item['online_45_num1'] = $online_45_num1;
            $item['online_60_num1'] = $online_60_num1;
            $item['online_75_num1'] = $online_75_num1;
            $item['online_gt75_num1'] = $online_gt75_num1;
            $item['online_15_num2'] = $online_15_num2 + $difference2;
            $item['online_30_num2'] = $online_30_num2;
            $item['online_45_num2'] = $online_45_num2;
            $item['online_60_num2'] = $online_60_num2;
            $item['online_75_num2'] = $online_75_num2;
            $item['online_gt75_num2'] = $online_gt75_num2;
            $item['userIdDay1_num'] = $userIdDay1Num;
            $item['userIdDay2_num'] = $userIdDay2Num;
            $item['mongo_num1'] = $mongo_num1;
            $item['mongo_num2'] = $mongo_num2;

        }
        return Res::ok(compact('list', 'total'));
    }

    // 获取成交数量
//    protected function getDealNum1($liveIdArr)
//    {
//        if (empty($liveIdArr)) return;
//        $liveIdStr = join(',',$liveIdArr);
//        $str = ' and `o`.`liveId` in (' . $liveIdStr . ') ';
//        $sql1 = "SELECT
//                o.wx_unionid,
//                m.uid
//                FROM xh_siyu_invitation_user as o left join `xh_siyu_sys_member` m on m.user_name = o.sender
//                 where o.del = 0 and o.signin_status =2 and o.chengjiao_status=0 ".$str." GROUP BY o.liveId, o.venue, o.wx_unionid";
//        $idItems = Db::query($sql1);
//
//        $str2 = '';
//        if(!empty($idItems)){
//            $salesIdArr = array_column($idItems, 'uid');
//            $salesIdArr = array_unique($salesIdArr);
//            $salesIdArr = array_map(function($item){return "'".$item."'";}, $salesIdArr);
//            $str2 = implode(',', $salesIdArr);
//            $str2 = ' and `o`.`tutorId` in  ( '.$str2.' ) ';
//
//            $userIdArr = array_column($idItems, 'wx_unionid');
//            $userIdArr = array_unique($userIdArr);
//            $userIdArr = array_map(function($item){return "'".$item."'";}, $userIdArr);
//            $userIdStr = implode(',', $userIdArr);
//            $str3 = ' and `o`.`wx_unionid` in  ( '.$userIdStr.' ) ';
//
//            $str2 .= $str3;
//        }
//        $sql = "select
//        sum(case when `o`.`state` =0 then 1 end) as no_pay_num,
//        sum(case when `o`.`from` =1 and `o`.`state` in (1,2,3,4)  then 1 end) as unlive_deal_num
//        from xh_siyu_order as o
//                INNER JOIN `xh_siyu_course` `c` ON `o`.`courseid` = `c`.`id`
//                LEFT JOIN `xh_siyu_user` `u` ON `o`.`wx_openid` = `u`.`openid`
//                LEFT JOIN `xh_siyu_sys_member` `m` ON `m`.`uid` = `o`.`tutorId`
//        where
//            o.del = 0
//            AND `u`.`del` = 0
//            AND `c`.`del` = 0
//        " . $str. $str2;
//        $res = Db::query($sql);
//
//        return $res ?? [];
//    }

    protected function getDealNum($liveIdArr)
    {
        if (empty($liveIdArr)) {
            return;
        }

        $liveIdStr = join(',', $liveIdArr);
        $sql1 = "SELECT
            IFNULL(
            sum(
                CASE
                    WHEN state =0 THEN 1
                    ELSE 0
                END
            ),0)AS no_pay_num
            FROM xh_siyu_order
            WHERE liveId IN ({$liveIdStr}) AND del=0
            AND wx_unionid IN (
                SELECT wx_unionid FROM xh_siyu_invitation_user WHERE signin_status=2 AND del=0 AND liveId IN ({$liveIdStr}) AND chengjiao_status=0 AND invitation_status=2
            )";
        $sql2 = "SELECT
            IFNULL(
            sum(
                CASE
                    WHEN `from` =1 and state in (1,2,3,4)  THEN 1
                    ELSE 0
                END
            ),0)AS unlive_deal_num
            FROM xh_siyu_order
            WHERE del=0
            AND wx_unionid IN (
                SELECT wx_unionid FROM xh_siyu_invitation_user WHERE signin_status=2 AND del=0 AND liveId IN ({$liveIdStr}) AND chengjiao_status=0 AND invitation_status=2
            )";
        $resNoPay = Db::query($sql1);
        $resUnliveDeal = Db::query($sql2);
        return compact('resNoPay', 'resUnliveDeal');
    }
    protected function getSalesDealNum($liveIdArr)
    {
        if (empty($liveIdArr)) {
            return;
        }

        $liveIdStr = implode(',', $liveIdArr);

        $str = ' and o.liveId in (' . $liveIdStr . ') ';

        $sql1 = "SELECT
                o.wx_unionid,
                m.uid
                FROM xh_siyu_invitation_user as o left join `xh_siyu_sys_member` m on m.user_name = o.sender
                 where o.del = 0 and o.signin_status =2 and o.chengjiao_status=0 " . $str . " GROUP BY o.liveId, o.venue, o.wx_unionid";
        $idItems = Db::query($sql1);
        $str2 = '';
        if (!empty($idItems)) {
            $salesIdArr = array_column($idItems, 'uid');
            $salesIdArr = array_unique($salesIdArr);
            $salesIdArr = array_map(function ($item) {return "'" . $item . "'";}, $salesIdArr);
            $str2 = implode(',', $salesIdArr);
            $str2 = ' and `o`.`tutorId` in  ( ' . $str2 . ' ) ';

            $userIdArr = array_column($idItems, 'wx_unionid');
            $userIdArr = array_unique($userIdArr);
            $userIdArr = array_map(function ($item) {return "'" . $item . "'";}, $userIdArr);
            $userIdStr = implode(',', $userIdArr);
            $str3 = ' and `o`.`wx_unionid` in  ( ' . $userIdStr . ' ) ';
            $str2 .= $str3;
        }

        $sql1 = "SELECT
                m.user_name,
                o.tutorId,
                sum( CASE WHEN `o`.`state` = 0  THEN 1 END ) AS no_pay_num
            FROM
                xh_siyu_order AS o
                INNER JOIN `xh_siyu_course` `c` ON `o`.`courseid` = `c`.`id`
	            LEFT JOIN `xh_siyu_user` `u` ON `o`.`wx_openid` = `u`.`openid`
	            LEFT JOIN `xh_siyu_sys_member` `m` ON `m`.`uid` = `o`.`tutorId`
            WHERE
                `o`.`del` = 0
                AND `u`.`del` = 0
                AND `c`.`del` = 0
                " . $str . $str2 . "
            GROUP BY
                o.tutorId";
        $sql2 = "SELECT
                m.user_name,
                o.tutorId,
                sum( CASE WHEN `o`.`from` = 1 and `o`.`state` in (1,2,3,4) THEN 1 END ) AS unlive_deal_num
            FROM
                xh_siyu_order AS o
                INNER JOIN `xh_siyu_course` `c` ON `o`.`courseid` = `c`.`id`
	            LEFT JOIN `xh_siyu_user` `u` ON `o`.`wx_openid` = `u`.`openid`
	            LEFT JOIN `xh_siyu_sys_member` `m` ON `m`.`uid` = `o`.`tutorId`
            WHERE
                `o`.`del` = 0
                AND `u`.`del` = 0
                AND `c`.`del` = 0
                " . $str2 . "
            GROUP BY
                o.tutorId";
        $resNoPay = Db::query($sql1);
        $resUnliveDeal = Db::query($sql2);
        return compact('resNoPay', 'resUnliveDeal');
    }

    /**
     * @param $param
     * @return \think\response\Json
     * Created by chenyawei on 2024/7/25
     * Description:直播数据-销售维度
     */
    public function liveSellerStat($param)
    {
        $whereMap['del'] = 0;
        $whereStr = '';
        if (!empty($param['live_group'])) {
            $whereMap['live_group'] = $param['live_group'];
            $whereStr = '  and m.live_group =' . "'" . $param['live_group'] . "'";
        }
        $limit = $param['limit'] ?? 10;
        $offset = $param['offset'] ?? 1;
        $fields = ' live_group,
                    sender,
                    MAX(CASE WHEN venue = 1 THEN id END) AS one_id,
                    MAX(CASE WHEN venue = 2 THEN id END) AS two_id,
                    MAX(CASE WHEN venue = 1 THEN start_time END) AS one_start_time,
                    MAX(CASE WHEN venue = 2 THEN start_time END) AS two_start_time,
                    MAX(CASE WHEN venue = 1 THEN yaoyue_num END) AS one_yaoyue_num,
                    MAX(CASE WHEN venue = 2 THEN yaoyue_num END) AS two_yaoyue_num,
                    MAX(CASE WHEN venue = 1 THEN daoke_num END) AS one_daoke_num,
                    MAX(CASE WHEN venue = 2 THEN daoke_num END) AS two_daoke_num,
                    sum(live_deal_num) AS live_deal_num';

        $countField = 'count(*) num';
        $sql = '( SELECT
                m.id,
                m.start_time,
                m.end_time,
                m.venue,
                m.live_group,
                u.sender,
                sum( CASE WHEN u.signin_status = 2 THEN 1 ELSE 0 END ) AS daoke_num,
                sum( CASE WHEN u.invitation_status = 2 THEN 1 ELSE 0 END ) AS yaoyue_num,
                sum( CASE WHEN u.signin_status = 2 AND chengjiao_status = 2 THEN 1 ELSE 0 END ) AS live_deal_num
                FROM
		            (
                    SELECT sender,wx_unionid, liveId, MAX( signin_status ) as signin_status, MAX( chengjiao_status ) as chengjiao_status, MAX( invitation_status ) as invitation_status FROM xh_siyu_invitation_user where del = 0 GROUP BY liveId, venue, wx_unionid
                    ) u
		        LEFT JOIN
		        xh_siyu_live_manager m ON u.liveId = m.id
	            WHERE m.del = 0 ' . $whereStr . '
	            GROUP BY
                u.sender,
                m.id  ) AS a
                GROUP BY
                sender
                ORDER BY
                start_time DESC';

        $total = Db::query('select ' . $countField . ' from ' . $sql);
        $total = count($total);
        $list = Db::query('select ' . $fields . ' from ' . $sql . ' limit ' . $limit . ' offset ' . $offset);
        $senderArr = array_column($list, 'sender');
        $senderFormat = [];
        if (!empty($senderArr)) {
            $senderArrUni = array_unique($senderArr);
            $senderArrUniStr = join(',', $senderArrUni);
            $whereSender[] = ['user_name', 'in', $senderArrUniStr];
            $senderNames = Db::name('siyu_sys_member')->where($whereSender)->field('user_name,nick_name')->select()->toArray();
            if (!empty($senderNames)) {
                $senderFormat = array_column($senderNames, 'nick_name', 'user_name');
            }

        }
        if (empty($list)) {
            return Res::ok(compact('list', 'total'));
        }
        $liveIdArr = [];
        $listFirst = $list[0];
        if (!empty($listFirst['one_id'])) {
            array_push($liveIdArr, $listFirst['one_id']);
        }
        if (!empty($listFirst['two_id'])) {
            array_push($liveIdArr, $listFirst['two_id']);
        }
        $dealInfoList = $this->getSalesDealNum($liveIdArr);
        $noPaySalesList = isset($dealInfoList['resNoPay']) ? $dealInfoList['resNoPay'] : [];
        $unliveSalesList = isset($dealInfoList['resUnliveDeal']) ? $dealInfoList['resUnliveDeal'] : [];
        $noPaySalesList = !empty($noPaySalesList) ? array_column($noPaySalesList, null, 'user_name') : [];
        $unliveSalesList = !empty($unliveSalesList) ? array_column($unliveSalesList, null, 'user_name') : [];
//        $d['remark'] = '销售直播统计数据:'.json_encode($dealInfoList);
//        DB::table('xh_siyu_user_remark')->save($d);
        // 订单表销售数组
//        $inviterName =  $orderSalesName = [];
//        $orderSalesName = array_keys($dealSalesList);
//        $inviterName = array_column($list, 'sender');
//        $diffName = array_diff($orderSalesName, $inviterName);
        foreach ($list as &$item) {
            $unliveItem = $nopayItem = [];
            $unliveItem = isset($unliveSalesList[$item['sender']]) ? $unliveSalesList[$item['sender']] : [];
            $nopayItem = isset($noPaySalesList[$item['sender']]) ? $noPaySalesList[$item['sender']] : [];
            // day1 到课率
            $item['one_daoke_rate'] = Helper::getRate($item['one_daoke_num'], $item['one_yaoyue_num']);
            // day2 到课率
            $item['two_daoke_rate'] = Helper::getRate($item['two_daoke_num'], $item['two_yaoyue_num']);
            // 课后成交数
            $item['unlive_deal_num'] = $unlive_deal_num = isset($unliveItem['unlive_deal_num']) ? $unliveItem['unlive_deal_num'] : 0;
            // 课后成交率
            $item['unlive_deal_rate'] = Helper::getRate($unlive_deal_num, $item['two_daoke_num']);
            // 直播成交率
            $item['live_deal_rate'] = Helper::getRate($item['live_deal_num'], $item['two_daoke_num']);
            // 总成交数
            $item['total_deal_num'] = $item['live_deal_num'] + $unlive_deal_num;
            // 未支付数
            $item['no_pay_num'] = isset($nopayItem['no_pay_num']) ? $nopayItem['no_pay_num'] : 0;
            $item['nick_name'] = isset($senderFormat[$item['sender']]) ? $senderFormat[$item['sender']] : '';
        }

        return Res::ok(compact('list', 'total'));

    }

    public static function getKey($val, $key, $ret, $arr)
    {
        $value = '';
        foreach ($arr as $item) {
            if ($val == $item[$key]) {
                $value = $item[$ret];
                break;
            }
        }
        return $value;
    }

    //siyu直播电话通知
    public function SendPhoneMessage()
    {
        $Live_list = LiveManagerService::getLiveStreamNow();
//        var_dump( $Live_list);die;
        if (!$Live_list) {
            return true;
        }
//        var_dump( $Live_list);die;
        $aliyun = new AliyunVmsController();

        //存在直播间号则查询订阅用户
        foreach ($Live_list as $key => $value) {
            $invitation_user_list = InvitationService::getUserList($value['id']);
            if (!$invitation_user_list) {
                continue;
            }
            $wx_unions = array_column($invitation_user_list, 'wx_unionid');
            //有值则循环调用阿里云接口电话信息通知
            $where = [];
            $where[] = ['wx_union_id', 'in', $wx_unions];
            $where[] = ['pay_state', '=', 1];
            $where[] = ['del', '=', 0];
            $where[] = ['tel', '>', 0];

            $user_order = Db::table('xh_order_1')->where($where)->distinct(true)->field('wx_union_id,tel')->select()->toArray();
//            var_dump($invitation_user_list);die;
            if (!$user_order) {
                continue;
            }

            //白名单用户
            $where2 = [];
            $where2[] = ['del', '=', 0];
            $where2[] = ['flag', '=', 1];
            $user_whitelist = Db::table('xh_voicetel_whitelist')->where($where2)->distinct(true)->field('del as wx_union_id,tel')->select()->toArray();

            $user_order2 = array_merge($user_order, $user_whitelist);

            foreach ($user_order2 as $k => $v) {
                //调用阿里云接口请求
                $aliyun->sendVms($v, $value['id']);
            }

        }

        return true;
    }

    //获取还有1分钟开播的直播间
    public static function getLiveStreamNow()
    {
        $where[] = ['start_time', '>', date('Y-m-d H:i:s', time())];
        $where[] = ['start_time', '<', date('Y-m-d H:i:s', (time() + env('ALI.audio_tel_time', 300)))];
        $where[] = ['status', '=', 0];
        $where[] = ['del', '=', 0];
//        $where[] = ['id', '=', 32];//模拟测试
        $data = Db::table('xh_siyu_live_manager')->where($where)->field('id')->select();
        return $data ? $data->toArray() : [];
    }

    public function updateRecordByRecordTaskId($record_task_id, $update_data)
    {
        return LiveManagerModel::where(["record_task_id" => $record_task_id])->update($update_data);
    }
}
